package kt.com.bilin.coin.api

import com.bilin.coin.BuildConfig
import com.bilin.coin.utils.GsonUtil
import com.bilin.coin.utils.LogUtlis
import com.bilin.coin.utils.SharedPreferencesUtils
import kt.com.bilin.coin.common.ServiceConfig
import kt.com.bilin.coin.helper.mohsi.MOSHI
import kt.com.bilin.coin.utils.Logger
import kt.com.bilin.coin.utils.SPUtils
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.net.Proxy
import java.util.*
import java.util.concurrent.TimeUnit

val API_SERVICE: ApiService
    get() = ApiHelper.getService()

/**
 *   @auther : Aleyn
 *   time   : 2019/09/04
 */
object ApiHelper {
    private const val TIME_OUT = 60L
    private var apiService: ApiService? = null

    fun getService(timeout: Long? = null): ApiService {
        if (timeout != null) {
            return createService(timeout)
        } else {
            if (apiService == null) {
                apiService = Retrofit.Builder()
                        .client(getOkHttpClient(TIME_OUT))
                        .addConverterFactory(MoshiConverterFactory.create(MOSHI))
                        .baseUrl(ServiceConfig.getCurrentServiceConfig().apiUrl)
                        .build()
                        .create(ApiService::class.java)
            }
            return apiService!!
        }
    }

    private fun createService(timeout: Long) = Retrofit.Builder()
            .client(getOkHttpClient(timeout))
            .addConverterFactory(MoshiConverterFactory.create(MOSHI))
            .baseUrl(ServiceConfig.getCurrentServiceConfig().apiUrl)
            .build()
            .create(ApiService::class.java)

    private fun getOkHttpClient(timeout: Long): OkHttpClient {
        return OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .addInterceptor(SignInterceptor())
                .addNetworkInterceptor(getHttpLoggingInterceptor())
                .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
                .cookieJar(BlCookieJar)
                .build()
    }

    fun getHttpLoggingInterceptor(): HttpLoggingInterceptor {
        //日志显示级别
        val level = HttpLoggingInterceptor.Level.BODY
        //新建log拦截器
        val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
//                if (BuildConfig.DEBUG) {
                    Logger.e("Api请求==>$message")
//                }
            }
        })
        loggingInterceptor.setLevel(level)
        return loggingInterceptor
    }
}

object BlCookieJar : CookieJar {
    override fun loadForRequest(url: HttpUrl): List<Cookie> = emptyList()
    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        val Cookie = SharedPreferencesUtils.getInstance().getString("Cookie", "")
        var mapCookie = GsonUtil.GsonToMaps<String?>(Cookie)
        if (mapCookie == null) {
            mapCookie = LinkedHashMap()
        }
        if (cookies.isNotEmpty()) {
            for (i in cookies.indices) {
                mapCookie[cookies[i].name] = cookies[i].value
                Logger.e(mapCookie.toString())
            }
            val strCookie = GsonUtil.GsonString(mapCookie)
            SharedPreferencesUtils.getInstance().saveData("Cookie", strCookie)
        }
    }

}